<template>
  <div class="p-2">
    <Forms ref="subForm" :data-from="formData" :list="pageSetting.TestTimerLog.search" name="TestTmeLog" :sub-loading="tableLoading" />
    <div class="flex">
      <div :style="{ width: drawer ? '50%' : '100%' }">
        <Table
          ref="main_Table"
          :column-list="mainTableColumn"
          :get-height="getHeight"
          :loading="tableLoading"
          name="TestTmeLog"
          :style="{ height: `${getHeight}px` }"
          :tables="tables"
        />
      </div>
      <div v-show="drawer" class="tab-content" style="width: 50%">
        <el-tabs v-model="tabName" v-loading="tabLoading" type="card" @tab-click="handleClick">
          <el-tab-pane v-for="(item, index) of tabList" :key="index" :label="item.title" :name="item.name">
            <div :style="{ height: `${getHeight - 100}px` }">
              <CodeEditor v-model="vuiCodevalue" :height="getHeight - 100" />
            </div>
          </el-tab-pane>
        </el-tabs>
        <vui-icon class="back" icon="arrow-right-circle-fill" @click="backTab" />
      </div>
    </div>
  </div>
</template>
<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import TestTimerLog from '../../components/json/TestTimerLog'
  import { getList } from '../../api/home.js'
  import Table from '../../components/table.vue'
  import Forms from '../../components/forms'
  import debounce from 'lodash/debounce'
  import { translateTitle } from '@/utils/i18n'
  import CodeEditor from '../../components/codeEditor'
  export default {
    name: 'TestTmeLog',
    components: { Table, Forms, CodeEditor },
    mixins: [Mixin],
    data() {
      return {
        // 选项卡列表
        tabList: [
          { name: 'first', title: translateTitle('Dams.ApplicationInterface.请求消息') },
          { name: 'second', title: translateTitle('Dams.ApplicationInterface.响应消息') },
          { name: 'thrid', title: translateTitle('Dams.ApplicationInterface.异常消息') },
        ],
        tabLoading: false,
        tabName: 'first',
        pageSetting: {
          TestTimerLog: { search: {} },
        },
        drawer: false,
        configSetting: {},
        apiParameter: {},
        show: false,
        formData: {},
        tables: {
          tableList: [],
          count: 0,
          pageSize: 150,
          limit: 1,
          name: 'TestTmeLog',
          operation: true,
          formatting: false,
        },
        clientHeight: 0,
        vuiCodevalue: '',
        tableLoading: false,
        unsubs: [],
        sqlList: [],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 160}`
      },
      mainTableColumn() {
        if (this.pageSetting.TestTimerLog.dialog) {
          let arr = this.pageSetting.TestTimerLog.dialog.form.field
          let newArr = []
          arr.forEach((v) => {
            if (v.type != 'button' && v.type != 'line' && !v.tableHidden && v.type != 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name,
                type: v.type,
              })
            }
            if (v.type == 'userPeriod') {
              newArr.push({
                label: v.label,
                porp: v.name.split(',')[0] + ',' + v.name.split(',')[1],
                type: v.type,
              })
            }
          })
          return newArr
        } else {
          return []
        }
      },
    },
    created() {
      this.init()
      if (this.$route.query) {
        this.apiParameter = this.$route.query
      }
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    methods: {
      translateTitle,
      handleClick() {
        switch (this.tabName) {
          case 'first':
            this.vuiCodevalue = this.tabList[0].value
            break
          case 'second':
            this.vuiCodevalue = this.tabList[1].value
            break
          case 'thrid':
            this.vuiCodevalue = this.tabList[2].value
            break
          default:
            break
        }
      },
      validateJSON(data) {
        if (typeof data == 'string') {
          try {
            var obj = JSON.parse(data)
            if (typeof obj == 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      jsonFormatting() {
        // this.formatting(this.validateJSON)
        if (!this.validateJSON(this.vuiCodevalue))
          return this.$baseMessage(translateTitle('Dams.ApplicationInterface.JSON格式错误'), 'error')
            ? JSON.stringify(JSON.parse(this.vuiCodevalue), null, 4)
            : translateTitle('Dams.ApplicationInterface.暂无数据')
      },
      backTab() {
        this.drawer = false
      },
      windowResize: debounce(function () {
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      async onSubmit(p) {
        let sub = p ? JSON.parse(JSON.stringify(p)) : []
        let obj = {
          '#LIMIT#': this.tables.limit,
          '#PAGE_SIZE#': this.tables.pageSize,
          ...sub[0],
        }
        if (p.length > 0 && p[0].DATE_TIME) {
          delete obj.DATE_TIME
          obj.DATE_TIME_START = p[0].DATE_TIME[0]
          obj.DATE_TIME_END = p[0].DATE_TIME[1]
        }
        this.tableLoading = true
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: 'system.log.server.timer.query',
        })
        this.tableLoading = false
        console.log(res)
        this.tables.tableList = res.data.data.data
        this.tables.count = res.data.data.count
      },
      setValue(arr, key) {
        let value = ''
        if (arr.length > 1) {
          for (let index = 0; index < arr.length; index++) {
            const element = arr[index]
            value = `${value}\n${element[key]}`
          }
        } else {
          value = arr[0][key]
        }
        return value
      },
      //查询msg日志
      async getMsg(REQUEST_UUID) {
        const p = JSON.parse(JSON.stringify(this.formData))
        if (p.DATE_TIME) {
          delete p.DATE_TIME
          p.DATE_TIME_START = this.formData.DATE_TIME[0]
          p.DATE_TIME_END = this.formData.DATE_TIME[1]
        }
        let obj = { ...p, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, REQUEST_UUID }
        this.tabLoading = true
        let method = 'system.log.server.timer.msg.query' //this.pageSetting.msgMethod
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: method,
        })
        this.tabLoading = false
        const request = res.data.data
        this.msgs = request.data[0]
        this.tabList.forEach((row) => {
          console.log(row)
          if (row.name == 'first') {
            row.value = this.setValue(request.data, 'REQUEST_MSG')
          }
          if (row.name == 'second') {
            row.value = this.setValue(request.data, 'RESPONSE_MSG')
          }
          if (row.name == 'thrid') {
            row.value = this.setValue(request.data, 'EXCEPTION_MSG')
          }
        })
        console.log(this.tabList)
        switch (this.tabName) {
          case 'first':
            this.vuiCodevalue = this.tabList[0].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          case 'second':
            this.vuiCodevalue = this.tabList[1].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          case 'thrid':
            this.vuiCodevalue = this.tabList[2].value || translateTitle('Dams.ApplicationInterface.暂无数据')
            break
          default:
            break
        }
      },
      eventInit() {
        //搜索事件
        this.$sub(`TestTmeLog_forms_on_search`, (data_arr) => {
          console.log(JSON.parse(JSON.stringify(data_arr)))
          this.formData = data_arr[0]
          this.tables.limit = 1
          this.onSubmit(data_arr)
        })
        this.unsubs.push(`TestTmeLog_forms_on_search`)
        this.$sub(`TestTmeLog_Table_clickOne_TestTmeLog`, (page_arr) => {
          console.log(page_arr)
          this.getMsg(page_arr[0].REQUEST_UUID)
          this.drawer = true
        })
        this.unsubs.push(`TestTmeLog_Table_clickOne_TestTmeLog`)
        this.$sub(`TestTmeLog_Table_on_TestTmeLog`, (page_arr) => {
          this.tables.limit = page_arr[0].limit
          this.tables.pageSize = page_arr[0].pageSize
          this.onSubmit([this.formData])
        })
        this.unsubs.push(`TestTmeLog_Table_on_TestTmeLog`)
      },
      async init() {
        this.configSetting = GFCD('dams')
        // this.nowJsonData().then((data) => {
        this.pageSetting = TestTimerLog
        this.show = true
        this.windowResize()
        this.eventInit()
        // })
      },
    },
  }
</script>
<style lang="scss">
  .tab-content {
    position: relative;
    .back {
      position: absolute;
      right: 0;
      top: -18px;
      cursor: pointer;
    }
    :deep() {
      .el-tabs__nav-prev,
      .el-tabs__nav-next {
        line-height: 20px;
      }
    }
  }
</style>
